﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Data.Linq;

namespace InSys.Documents
{
    using InSys.Alarm;
//    public struct historydata
//    {
//        public DateTime datetime;
//        public string name;
//    }

    public partial class FormDocument : Form
    {
        enum usermode { insert, edit, notdefined };
        enum SelectDocumentsMode { work = 0, alarm = 1}; // Выбраные рабочие документы / документы, о которых необходимо напомнить

        private SelectDocumentsMode currentSelectDocumentsMode = SelectDocumentsMode.work;
        private usermode UserMode = usermode.notdefined;
        private int id_user_login = 0;
        private int id_user_department = 0;
        private DateTime WorkDate = Program.gWorkDate;
        private MapTestLinqDataContext db = new MapTestLinqDataContext(Properties.Settings.Default.testlinqConnectionString);
        private MapTestLinqDataContext dbReadOnly = new MapTestLinqDataContext(Properties.Settings.Default.testlinqConnectionString); // используется только для получения информации о движении документа и параметрах документа.
        private document CurrentDocument = null;
        private IEnumerable<document> queryDocument;
        private object queryListObj;
        private IAlarm alarmObject;
        private FormSearchDocument srch_frm;

        private FormWaitWindow wnd = null;
        private bool curchng;
        private bool modified;
        private bool Modified
        {
            set
            {
                modified = value;
                if (true == value)
                    Text = "Документы *";
                else
                    Text = "Документы";
            }
            get { return modified; }
        }
        private AccessUserLoginInfo info;

        public FormDocument()
        {
            InitializeComponent();
            info = new AccessUserLoginInfo();
            this.id_user_department = 0;
            this.id_user_login = 0;
            alarmObject = new AlarmObject();
            checkBoxRemind.Checked = false;
            checkBoxRemindChanged();
        }

        private void checkBoxRemindChanged()
        {
            dateTimePickerRemind.Enabled = checkBoxRemind.Checked;
        }

        public FormDocument(int id_user, int id_department)
            : this()
        {
            this.id_user_login = id_user;
            this.id_user_department = id_department;
        }

        private void BackgroundInitData()
        {
            
            // заполнение таблицы для person_documentDataGridView
            switch (currentSelectDocumentsMode)
            {
                case SelectDocumentsMode.work:
                    queryDocument = ClassWorkWithDB.getListDocument(db, id_user_login, WorkDate, Program.gKindDocument);
                    break;
                case SelectDocumentsMode.alarm:
                    queryDocument = alarmObject.getAlarmedDocuments(id_user_login, WorkDate);
                    break;
            }

        }

        private void InitData()
        {
            dbReadOnly.ObjectTrackingEnabled = false;

            // рабочая дата системы
            toolStripStatusLabelWorkDate.Text = "Рабочая дата: "+WorkDate.ToShortDateString();
            // выбор пользователя системы и отдела
            FormSelectUser formSelectUser = new FormSelectUser();
            toolStripStatusLabelDepartment.Text = "отдел: не выбран";
            toolStripStatusLabelUser.Text = "пользователь: не выбран";

            if (0 != id_user_login)
            {
                toolStripStatusLabelUser.Text = string.Format("пользователь: {0}", info.GetUserNameById(id_user_login));
                labelNameRemind.Text = info.GetUserNameById(id_user_login);
            }
            if (0 != id_user_department)
            {
                toolStripStatusLabelDepartment.Text = string.Format("отдел: {0}", info.GetDepartmentNameById(id_user_department));
            }
                //if (DialogResult.OK == formSelectUser.ShowDialog())
                //{
                //    id_user_login = formSelectUser.IdUser;
                //    id_user_department = formSelectUser.IdDepartment;
                //    toolStripStatusLabelDepartment.Text = "отдел: " + formSelectUser.NameDepartment;
                //    toolStripStatusLabelUser.Text = "пользователь: " + formSelectUser.NameUser;
                //}
                //else
                //{
                //    id_user_login = 0;
                //    id_user_department = 0;
                //    toolStripStatusLabelDepartment.Text = "отдел: не выбран";
                //    toolStripStatusLabelUser.Text = "пользователь: не выбран";
                //}
                wnd = new FormWaitWindow();
                wnd.Description = "Загрузка данных. Подождите";
                wnd.Show();
                //ClearBindingSourceDocumentInfoPanel();
                backgroundWorkerInitData.RunWorkerAsync();
                while (this.backgroundWorkerInitData.IsBusy)
                {
                    // Keep UI messages moving, so the form remains 
                    // responsive during the asynchronous operation.
                    Application.DoEvents();
                }
                documentBindingSource.DataSource = queryDocument;
                //ChangeBindingSourceDocumentInfoPanel(documentBindingSource);
                UserMode = usermode.edit;
                EnableDocumentInfoPanel(UserMode != usermode.notdefined);
                IEnumerable<string> kndDoc = (from str in dbReadOnly.kindDocument where str.id == Program.gKindDocument select str.kind_document);
                if (kndDoc.Count() > 0)
                    toolStripStatusLabelKindDocument.Text = kndDoc.First();
                else
                    toolStripStatusLabelKindDocument.Text = "Вид документа не выбран";
                toolStrip1.Enabled = true;
                userControlSelectUser1.ActualDate = WorkDate;
                wnd.Close();
                wnd = null;
        }

        private void InitData(bool withFilter)
        {
            if (false == withFilter)
            {
                InitData();
                return;
            }
            // рабочая дата системы
            toolStripStatusLabelWorkDate.Text = "Рабочая дата: " + WorkDate.ToShortDateString();
            // выбор пользователя системы и отдела
            FormSelectUser formSelectUser = new FormSelectUser();

            if (0 == id_user_login)
            {
                if (DialogResult.OK == formSelectUser.ShowDialog())
                {
                    id_user_login = formSelectUser.IdUser;
                    id_user_department = formSelectUser.IdDepartment;
                    toolStripStatusLabelDepartment.Text = "отдел: " + formSelectUser.NameDepartment;
                    toolStripStatusLabelUser.Text = "пользователь: " + formSelectUser.NameUser;
                    labelNameRemind.Text = formSelectUser.NameUser;
                }
                else
                {
                    id_user_login = 0;
                    id_user_department = 0;
                    toolStripStatusLabelDepartment.Text = "отдел: не выбран";
                    toolStripStatusLabelUser.Text = "пользователь: не выбран";
                    labelNameRemind.Text = "";
                }
            }
            wnd = new FormWaitWindow();
            wnd.Description = "Загрузка данных. Подождите";
            wnd.Show();
            backgroundWorkerInitDataWithFilter.RunWorkerAsync();
            while (this.backgroundWorkerInitDataWithFilter.IsBusy)
            {
                // Keep UI messages moving, so the form remains 
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
            //ClearBindingSourceDocumentInfoPanel(); // TO DO 
            documentBindingSource.DataSource = queryDocument;
            //ChangeBindingSourceDocumentInfoPanel(documentBindingSource);
            UserMode = usermode.edit;
            EnableDocumentInfoPanel(UserMode != usermode.notdefined);
            toolStrip1.Enabled = true;
            userControlSelectUser1.ActualDate = WorkDate;
            wnd.Close();
            wnd = null;
        }

        private void BackTransferDocument(BackgroundWorker worker, DoWorkEventArgs e)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                try
                {
                    // Осуществляем передачу документа
                    int id_person = userControlSelectUser1.IdUser;
                    int id_document = (person_documentDataGridView.CurrentRow.DataBoundItem as document).id_document;
                    ClassWorkWithDB.TransferDocument(db, id_document, id_person, dateTimePickerTransfer.Value, textBoxComment.Text);
                    // Осуществляем обновление информации о напоминании
                    alarmObject.ClearAlarm(id_person, id_document); // Снимаем с документа все напоминания, установленные тем пользователем, коотрому направляемдокумент
                    if (checkBoxRemind.Checked == true)
                        alarmObject.SetAlarm(id_user_login, id_document, dateTimePickerRemind.Value); // если необходимо, устанавливаем напоминание для пользователя, от имени которого осуществлен вход в систему
                }
                catch (Exception)
                {
                    MessageBox.Show("Ошибка при передаче документа");
                }
            }
        }

        private void BackRefreshPersonDocument(BackgroundWorker worker, DoWorkEventArgs e)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                try
                {
                    refreshPersonDocument();
                }
                catch (Exception)
                {
                    MessageBox.Show("Ошибка при обновлении информации о документе");
                }
            }
        }

        private void TransferDocument()
        {
            wnd = new FormWaitWindow();
            wnd.Description = "Выполняется передача документа. Подождите";
            wnd.Show();
            backgroundWorkerTransferDocument.RunWorkerAsync();
            while (this.backgroundWorkerTransferDocument.IsBusy)
            {
                // Keep UI messages moving, so the form remains 
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
            wnd.Close();
            wnd = null;

            wnd = new FormWaitWindow();
            wnd.Description = "Обновляется информация. Подождите";
            //ClearBindingSourceDocumentInfoPanel();
            wnd.Show();
            backgroundWorkerRefreshDocument.RunWorkerAsync();
            while (this.backgroundWorkerRefreshDocument.IsBusy)
            {
                Application.DoEvents();
            }
            wnd.Close();
            wnd = null;
            documentBindingSource.DataSource = queryDocument;
            //ChangeBindingSourceDocumentInfoPanel(documentBindingSource);
            MessageBox.Show(Properties.Resources.TransferSuccessfull);
            if (checkBoxFix.Checked == false)
            {
                dateTimePickerTransfer.Value = DateTime.Now;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonMove_Click(object sender, EventArgs e)
        {
            TransferDocument();
        }

        private void newToolStripButton_Click(object sender, EventArgs e)
        {
            if (UserMode == usermode.insert) return; // мы и так в режиме добавления документа
            try
            {
                documentBindingSource.AddNew();
                CurrentDocument = documentBindingSource.Current as document;
                CurrentDocument.date = DateTime.Now;
                CurrentDocument.description = "";
                CurrentDocument.enterprise = "";
                CurrentDocument.number = "";
                CurrentDocument.id_kindDocument = Program.gKindDocument;
                CurrentDocument.address="";
                CurrentDocument.local_id = "";
                UserMode = usermode.insert;
//                ChangeBindingSourceDocumentInfoPanel(CurrentDocument);
                EnableDocumentInfoPanel(true);
            }
            catch
            {
                MessageBox.Show("Ошибка при регистрации нового документа");
            }
        }


        private void EnableDocumentInfoPanel(bool enable)
        {
            dateDateTimePicker.Enabled = enable;
            numberTextBox.Enabled = enable;
            enterpriseTextBox.Enabled = enable;
            descriptionTextBox.Enabled = enable;
            LocalIDTextBox.Enabled = enable;
        }

        //private void ClearBindingSourceDocumentInfoPanel()
        //{
        //    dateDateTimePicker.DataBindings.Clear();
        //    dateDateTimePicker.Value = DateTime.Now;
        //    numberTextBox.DataBindings.Clear();
        //    numberTextBox.Text = "";
        //    enterpriseTextBox.DataBindings.Clear();
        //    enterpriseTextBox.Text = "";
        //    descriptionTextBox.DataBindings.Clear();
        //    descriptionTextBox.Text = "";
        //    LocalIDTextBox.DataBindings.Clear();
        //    LocalIDTextBox.Text = "";
        //    textBoxAddress.DataBindings.Clear();
        //    textBoxAddress.Text = "";
        //}

        //private void ChangeBindingSourceDocumentInfoPanel(object DataSource)
        //{
        //    //ClearBindingSourceDocumentInfoPanel();
        //    dateDateTimePicker.DataBindings.Add(new Binding("value", DataSource, "date", true));
        //    numberTextBox.DataBindings.Add(new Binding("text", DataSource, "number"));
        //    enterpriseTextBox.DataBindings.Add(new Binding("text", DataSource, "enterprise"));
        //    descriptionTextBox.DataBindings.Add(new Binding("text", DataSource, "description"));
        //    LocalIDTextBox.DataBindings.Add(new Binding("text", DataSource, "local_id"));
        //    textBoxAddress.DataBindings.Add(new Binding("text", DataSource, "address"));
        //}

        private void EndEditSourceDocumentInfoPanel(object DataSource)
        {
            dateDateTimePicker.BindingContext[DataSource].EndCurrentEdit();
            numberTextBox.BindingContext[DataSource].EndCurrentEdit();
            numberTextBox.BindingContext[DataSource].EndCurrentEdit();
            enterpriseTextBox.BindingContext[DataSource].EndCurrentEdit();
            descriptionTextBox.BindingContext[DataSource].EndCurrentEdit();
            LocalIDTextBox.BindingContext[DataSource].EndCurrentEdit();
            textBoxAddress.BindingContext[DataSource].EndCurrentEdit();
        }

        private void FormDocuments(object sender, EventArgs e)
        {
            InitData();
            modified = false;
            Text = "Документы";
            curchng = false;
            srch_frm = null;
            DisplayHistoryDocumentToolStripComboBox.SelectedIndex = 1;
            toolStripComboBoxTypeDocuments.SelectedIndex = 0;
            dateTimePickerTransfer.Value = DateTime.Now;
            dateTimePickerTransfer.CustomFormat = "dd'/'MM'/'yyyy HH':'mm tt";
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {

                // Сохраняем документ
                
                if (UserMode == usermode.insert)
                {
                    EndEditSourceDocumentInfoPanel(CurrentDocument);
                    db.document.InsertOnSubmit(CurrentDocument);
                    db.SubmitChanges();
                    // Сохраняем первичное движение документа
                    ClassWorkWithDB.TransferDocument(db, CurrentDocument.id_document, id_user_login, DateTime.Now,"Первичный ввод в систему");
                    // обновляем таблицу
                    wnd = new FormWaitWindow();
                    wnd.Description = "Обновляется информация. Подождите";
                    wnd.Show();
                    backgroundWorkerRefreshDocument.RunWorkerAsync();
                    while (this.backgroundWorkerRefreshDocument.IsBusy)
                    {
                        Application.DoEvents();
                    }
                    documentBindingSource.DataSource = queryDocument;
                    //ChangeBindingSourceDocumentInfoPanel(documentBindingSource);
                    wnd.Close();
                    MessageBox.Show(Properties.Resources.DataSaved);
                    //refreshPersonDocument();
                }
                if (UserMode == usermode.edit)
                {
                    EndEditSourceDocumentInfoPanel(documentBindingSource);
                    db.SubmitChanges();
                    MessageBox.Show(Properties.Resources.DataSaved);
                }

                //ClearBindingSourceDocumentInfoPanel();
                UserMode = usermode.edit;
                EnableDocumentInfoPanel(true);
                Modified = false;
            }
            catch (Exception err)
            {
                MessageBox.Show("Ошибка при сохранении документа\n\r"+err.ToString());
            }
        }

        private void refreshPersonDocument()
        {
            var queryDocument = ClassWorkWithDB.getListDocument(db, id_user_login, WorkDate, Program.gKindDocument);
            documentBindingSource.DataSource = queryDocument;
        }

        private void отчетToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FormReport form = new FormReport();
            //form.Show();
        }

        private void отчетВсеДокументыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FormReportAllDocuments form = new FormReportAllDocuments();
            //form.Show();
        }

        private void отделToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormDepartmentList form = new FormDepartmentList();
            form.Show();
        }

        private void должностьToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            FormPostList form = new FormPostList();
            form.Show();
        }

        private void сотрудникToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FormPersonList form = new FormPersonList();
            form.Show();
        }

        private void сотрудинкиПоОтделамToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            FormPersonDepartment form = new FormPersonDepartment();
            form.Show();
        }

        private void описанияToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FormDescription form = new FormDescription();
            form.Show();
        }

        private void сменаПользователяToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ClearBindingSourceDocumentInfoPanel();
            id_user_login = 0; // необходимо для того, чтобы при обновлении данных открылся диалог выбора пользователя системы
            InitData();
        }

        private void person_documentDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void userControlSelectUser1_UserControlSelectUserEvent(object sender, EventArgs e)
        {
            TransferDocument();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            BackTransferDocument(worker, e);
        }

        private void backgroundWorkerRefreshDocument_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            BackrefreshDocument(worker, e);
        }

        private void BackrefreshDocument(BackgroundWorker worker, DoWorkEventArgs e)
        {
            queryDocument = ClassWorkWithDB.getListDocument(db, id_user_login, WorkDate, Program.gKindDocument);
        }

        private void backgroundWorkerInitData_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundInitData();
        }

        private void documentBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            if (curchng == true)
            {
                curchng = false;
            }
            else
            {
                Modified = true;
            }
        }

        private object getHistoryData()
        {
            object result = null;
            try
            {
                int mdocument = -1;
                if (documentBindingSource.CurrencyManager.Current is document)
                    mdocument = ((documentBindingSource.CurrencyManager.Current) as document).id_document; 
                result = from item in dbReadOnly.person_documents where item.id_document == mdocument join person in dbReadOnly.persons on item.id_person equals person.id_person orderby item.datetime descending select new { item.datetime, person.name, item.description };
            }
            catch (Exception)
            {
                return null;
            }
            return result;
        }

        private void documentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            curchng = true;            
            if (1 == DisplayHistoryDocumentToolStripComboBox.SelectedIndex)
            {
                // обновляем данные таблицы истории перемещения документа
                queryListObj = getHistoryData(); 
                HistoryDataGridView.DataSource = queryListObj;
                ChangeHistoryDataGridViewHeader();
            }
        }

        private void ChangeHistoryDataGridViewHeader()
        {
            try
            {
                HistoryDataGridView.Columns[0].HeaderText = "Дата";
                HistoryDataGridView.Columns[1].HeaderText = "Сотрудник";
                HistoryDataGridView.Columns[2].HeaderText = "Комментарий";
            }
            catch (Exception)
            {
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (null == srch_frm)
            {
                srch_frm = new FormSearchDocument();
                srch_frm.Disposed += new EventHandler(srch_frm_Disposed);
                srch_frm.FormSearchEvent += new FormSearchDocument.FormSearchDocumentEventHandler(srch_frm_FormSearchEvent);
                srch_frm.UserID = id_user_login;
                srch_frm.NotUsed = false;
                srch_frm.Show();
            }
            srch_frm.Activate();
        }

        void srch_frm_FormSearchEvent(object sender, EventArgs e)
        {
            srch_frm.FormSearchEvent -= srch_frm_FormSearchEvent;
            InitData(true);
            srch_frm.FormSearchEvent += new FormSearchDocument.FormSearchDocumentEventHandler(srch_frm_FormSearchEvent);
        }

        void srch_frm_Disposed(object sender, EventArgs e)
        {
            srch_frm = null;
        }

        private void backgroundWorkerInitDataWithFilter_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundInitData(true);
        }

        private void BackgroundInitData(bool p)
        {
            if (srch_frm==null || false == p)
            {
                BackgroundInitData();
                return;
            }
            queryDocument = ClassWorkWithDB.getListDocument(db, WorkDate, srch_frm, Program.gKindDocument);
        }

        private void DisplayHistoryDocumentToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DisplayHistoryDocumentToolStripComboBox.SelectedIndex == 0)
            {
                HistoryDataGridView.DataSource = null;
            }
            else
            {
                queryListObj = getHistoryData();
                HistoryDataGridView.DataSource = queryListObj;
                ChangeHistoryDataGridViewHeader();
            }
        }

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormExcelImport frm = new FormExcelImport();
            frm.Show();
        }

        private void видыДокументовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormKindDocuments frm = new FormKindDocuments();
            frm.Show();
        }

        private void toolStripButtonSelectKindDocument_Click(object sender, EventArgs e)
        {
            FormSelectKindDocument frm = new FormSelectKindDocument();
            frm.KindDocument = Program.gKindDocument;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (Program.gKindDocument == frm.KindDocument)
                    return;
                Program.gKindDocument = frm.KindDocument;
                IEnumerable<string> kndDoc = (from str in dbReadOnly.kindDocument where str.id == Program.gKindDocument select str.kind_document);
                if (kndDoc.Count() > 0)
                    toolStripStatusLabelKindDocument.Text = kndDoc.First();
                else
                    toolStripStatusLabelKindDocument.Text = "Вид документа не выбран";
                //ClearBindingSourceDocumentInfoPanel();
                InitData();
            }
        }

        private void documentBindingSource_DataError(object sender, BindingManagerDataErrorEventArgs e)
        {
            MessageBox.Show("Error");
        }

        private void отчToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormReportAddedDocumentsByPeriod frm = new FormReportAddedDocumentsByPeriod(id_user_login);
            frm.Show();
        }

        private void отчетПоКоличествуДокументовВОбработкеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                FormReportDocumentCountByPerson frm = new FormReportDocumentCountByPerson(id_user_login);
                frm.Show();
            }
            catch (Exception)
            {
                MessageBox.Show(Properties.Resources.ReportLoadError);
            }
        }

        private void checkBoxFix_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePickerTransfer.Enabled = !checkBoxFix.Checked;
        }

        private void реестрЗарегистрированныхДокументовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                FormReportListDocumentByUser frm = new FormReportListDocumentByUser(id_user_login);
                frm.Show();
            }
            catch (Exception)
            {
                MessageBox.Show(Properties.Resources.ReportLoadError);
            }
        }

        private void toolStripComboBoxTypeDocuments_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (currentSelectDocumentsMode != (SelectDocumentsMode)toolStripComboBoxTypeDocuments.SelectedIndex)
            {
                currentSelectDocumentsMode = (SelectDocumentsMode)toolStripComboBoxTypeDocuments.SelectedIndex;
                InitData();
            }
        }

        private void checkBoxRemind_CheckedChanged(object sender, EventArgs e)
        {
            checkBoxRemindChanged();
        }

        private void toolStripComboBoxTypeDocuments_Click(object sender, EventArgs e)
        {
            
        }

        private void toolStripButtonHierarchy_Click(object sender, EventArgs e)
        {
            try
            {
                if (null == documentBindingSource.DataSource) return;
                document curDoc = documentBindingSource.Current as document;
                if (null == curDoc) return;
                FormEditLinkDocument frm = new FormEditLinkDocument();
                frm.DataContext = db;
                frm.CurrentDocument = curDoc;
                frm.Show();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка открытия формы.");
            }
        }

        private void toolStripButtonLookHierarchy_Click(object sender, EventArgs e)
        {
            try
            {
                if (documentBindingSource.DataSource == null) return;
                document cur_doc = documentBindingSource.Current as document;
                if (null == cur_doc) return;
                FormHiearachyDocumentView frm = new FormHiearachyDocumentView();
                frm.DataContext = db;
                frm.FillTree(cur_doc);
                frm.Show();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка. Иерархия не может быть отображена.");
            }
        }
    }
}
